define(
	[
		'require',
		'./overview_ctrl'
	],
	function(require){
		var Controller = Ember.Controller.extend({
		needs: ["businessCenter","businessOverview"],

		timePoint: Ember.computed.oneWay('controllers.businessCenter.timePoint'),

		isCenterTradingMode: Ember.computed.alias('controllers.businessCenter.isTradingMode'),

		isOverviewTradingMode: Ember.computed.alias('controllers.businessOverview.isTradingMode'),

		setup: function(startTime,pinTimePoint){
			this.set("businessSwitch",overviewOrCenterSwitch);
			this.set("businessSwitchName",overviewOrCenterSwitch==='business'?'交易模式':'应用模式');
			this.set("sequenceChartDisplayMode", "detail");
			this.requireApplications();

			this.width = $(".business-detail-top").width()-310;
			if(!pinTimePoint){
				if(startTime){
					startTime = parseInt(startTime);
					this.stopRealTimeMode();
					this.set("pinTimePoint", startTime);
					this.set("selectedFormatedDate", startTime);

					startTime = new Date(startTime);
					startTime.setMinutes(0);
					startTime.setSeconds(0);
					startTime.setMilliseconds(0);
					this.requirePerformances(+startTime);
				}else{

					this.requirePerformances();
					this.startRealTimeMode();
				}
			}else{
				var startDate,endDate;
					endDate = new Date(new Date() - timeD_value);
					endDate.setMinutes(endDate.getMinutes()-1);
					endDate.setSeconds(0);
					endDate.setMilliseconds(0);
					startDate = new Date(+endDate)
					startDate.setHours(startDate.getHours()-1);
					this.requirePerformances(+startDate);

				startTime = parseInt(startTime);
				
				this.startRealTimeMode();

				this.set("timePoint",startTime);
				this.set("clickTimePoint",startTime);
				this.set("isSelectedTime",true);

				this.set("pinTimePoint", startTime);
			}
			
		},
		
		modelData: function(model,panelId){
			var ctrl = this;
			if(panelId == "detail"){
				panelId = "system";
			}else if(panelId == "overview"){
				panelId = "business";
			}else{
				panelId = "system";
			}
			return this.store.ajax("GET", "applications/"+model.id,{"panelId":panelId})
			.then(function(response){
				var app = response.application;
				Ember.A(app.topoNodes);
				Ember.A(app.relations);
				ctrl.set("model",app);
			});
		},

		otherApps: Ember.computed(function(key, value){
			var ctrl = this;
			if(arguments.length == 1){
				return Ember.A([{name: "加载中..."}]);
			}else{
				var modelId = this.get("model.id");
				var otherApps = value.filter(function(app){
					return app.id != modelId;
				});
				return Ember.A(otherApps);
			}
		}),

		modelPerformancesChange: Ember.observer("model.performances", function(){
			var model = this.get("model");
			if(model && model.performances){
				var performances = model.performances;
				this.set("sequenceDataOneHour", performances);

				var pinTimePoint = this.get("pinTimePoint");
				if(performances.length > 0){
					if(pinTimePoint && pinTimePoint < performances[0].timestamp){
						this.set("pinTimePoint", null);
					}
					if(!this.get("pinTimePoint")){
						var timePoint = performances[performances.length-1].timestamp;
						this.set("timePoint", timePoint);
					}
				}
				
				this.realTimeCallbacks.forEach(function(context){
					context.method.apply(context.target, context.args);
				});
			}
		}),

		today: Ember.computed(function(){
			return APM.util.formatDate(new Date(new Date() - timeD_value), "D");
		}),

		/*
			实时模式开关
		*/
		isRealtimeMode: true,

		selctedDate: Ember.computed(function(){
			if(arguments.length == 1){
				var now = new Date(new Date() - timeD_value);
				now = new Date(now.getFullYear(), now.getMonth(), 1);
				if( isLocalDebugModel ){
					now = new Date(2014, 9, 1, 0, 0, 0);
				}
				return now;
			}
		}),

		historyDate: Ember.computed(function(key, value){
			if(arguments.length == 1){

				var now = new Date(new Date() - timeD_value);
				now = new Date(now.getFullYear(), now.getMonth(), 1);
				if( isLocalDebugModel ){
					now = new Date(2014, 9, 1, 0, 0, 0);
				}
				return {
					name: APM.util.formatDate(now, "Y"),
					value: +now,
					start: now.getTime(),
					end: now.setMonth(now.getMonth()+1)-24*3600000
				};
			}else{
				var date = new Date(value);
				return {
					name: APM.util.formatDate(date, "Y"),
					value: +date,
					start: date.getTime(),
					end: date.setMonth(date.getMonth()+1)-24*3600000
				};
			}
		}),

		selectedFormatedDate: Ember.computed(function(key, value){
			if(arguments.length == 1){
				return "";
			}else{
				var date = new Date(value);
				if(Ember.isBlank(value)){
					return "";
				}else{
					var hours = date.getHours();
					return date.getDate()+"日 " + hours + ":00 - " + (hours+1) + ":00";			
				}
			}
		}),

		selctedDateChange: Ember.observer("selctedDate", function(){
			this.send("queryByMonth");
		}),

		/*
			时序图显示模式, overview: 以1小时为最小粒度的概览模式
							detail	: 以1分钟为小粒度的详情模式
		*/
		sequenceChartDisplayMode: "detail",

		isSequenceChartDisplayDetail: Ember.computed('sequenceChartDisplayMode', function() {
			return this.get('sequenceChartDisplayMode') == 'detail';
		}),

		sequenceData: Ember.computed("sequenceChartDisplayMode", "sequenceDataOneHour", "sequenceDataOneMonth", function(key, value){
			if(arguments.length == 1){
				var a = Ember.A();
				if(this.sequenceChartDisplayMode == "detail"){
					return this.get("sequenceDataOneHour")||a;
				}else{
					return this.get("sequenceDataOneMonth")||a;
				}
			}else{
				return value;
			}
		}),

		/*
			启动实时模式
		*/
		startRealTimeMode: function(){
			if(this.timeTicket){
				return;
			}

			this.set("isRealtimeMode", true);

			this.set("clickTimePoint", null);

			_requireData(this);

			function _requireData(ctrl){
				var interval = 60000;
				if(isLocalDebugModel){
					interval = 6000;
				}
				ctrl.timeTicket = setTimeout(function() {
					ctrl.requirePerformances()
					.then(function(response){
						_requireData(ctrl);
					});
				}, interval);
			}
		},

		/*
			停止动实时模式
		*/
		stopRealTimeMode: function(){
			clearTimeout(this.timeTicket);
			this.timeTicket = null;

			this.set("isRealtimeMode", false);
		},

		realTimeCallbacks: Ember.A(),

		/*
			新增实时模式钩子方法, 子界面需要在实时模式请求时, 同步执行的方法时, 调用该方法.
		*/
		addRealTimeHook: function(target, method /*, args */) {
			if (!method) {
				method = target;
				target = null;
			}
			if (Ember.typeOf(method) == "string") {
				method = target[method];
			}

			var args = [].slice.call(arguments, 2);

			var isUniq = true;
			this.realTimeCallbacks.forEach(function(obj){
				if(method == obj.method && target == obj.target){
					isUniq = false;
				}
			});

			if(!isUniq){
				return;
			}

			this.realTimeCallbacks.push({
				target: target,
				method: method,
				args: args
			});
		},

		removeRealTimeHook: function(target, method){
			if (!method) {
				method = target;
				target = null;
			}

			if (Ember.typeOf(method) == "string") {
				method = target[method];
			}

			var index,
				callbacks = this.realTimeCallbacks;
			callbacks.forEach(function(context, i){
				if(context.method == method){
					index = i;
				}
			});
			callbacks.removeObject(callbacks.objectAt(index));
		},

		_setAppXAxisTime: function(){
			this.get("controllers.businessCenter")
				._setAppXAxisTime([this.get("model")]);
		},

		/*
			向服务端请求业务系统列表
		*/
		requireApplications: function(){
			var ctrl = this;
			return this.get("controllers.businessCenter").requireApplications()
			.then(function(applications){
				ctrl.set("otherApps", applications);
				return applications;
			});
		},

		/*
			向服务端请求业务系统
		*/
		requireApplication: function(id){
			return this.store.ajax("GET", "applications/"+id)
			.then(function(response){
				return response.application;
			});
		},

		// requirePerformancesByHalfOnehour: function(){
		// 	var  ctrl = this;
		// 	var startDate = ctrl.get("controllers.businessOverview").calculationTime().startDate;
		// 	var endDate = ctrl.get("controllers.businessOverview").calculationTime().endDate;
		// 	return this.store.ajax("GET", "performances", {
		// 		appIds: appId,
		// 		startDate: +startDate,
		// 		endDate: +endDate
		// 	})
		// 	.then(function(response){
		// 		var performances;
		// 		if(response){
		// 			performances = Ember.A(response[appId]);
		// 			ctrl.set("model.threshold", response.threshold);
		// 		}else{
		// 			performances = Ember.A();
		// 		}
		// 		performances = ctrl.get("controllers.businessCenter")
		// 			.performancesCompletion(performances, startDate, endDate);

		// 		ctrl.set("model.performances", performances);
		// 		ctrl._setAppXAxisTime();
		// 		return performances;
		// 	});
		// },
		/*
			向服务端请求某一小时内的详细性能数据
			@param {number} time 开始时间的时间值
		*/
		requirePerformances: function(time){
			var ctrl = this,
				appId = this.get("model.id"),
				startDate, endDate;
			if(time){
				startDate = new Date(time);
				endDate = new Date(+startDate)
				endDate.setHours(endDate.getHours()+1);
			}
			// else if(overviewOrCenterSwitch == "business"){
			// 	startDate = ctrl.get("controllers.businessOverview").calculationTime().startDate;
			// 	endDate = ctrl.get("controllers.businessOverview").calculationTime().endDate;
			// }  //30分钟数据
			else{
				endDate = new Date(new Date() - timeD_value);
				endDate.setMinutes(endDate.getMinutes()-1);
				endDate.setSeconds(0);
				endDate.setMilliseconds(0);
				startDate = new Date(+endDate)
				startDate.setHours(startDate.getHours()-1);
			}
			//开发调试模式参数
			if( isLocalDebugModel ){
				if(time){
					startDate = new Date(1412132400000);
					endDate = new Date(+startDate)
					endDate.setHours(endDate.getHours()+1);
				}else{
					endDate = new Date(2014, 9, 1, 12, 0, 0);
					startDate = new Date(+endDate)
					startDate.setHours(startDate.getHours()-1);
				}
			}

			return this.store.ajax("GET", "performances", {
				appIds: appId,
				startDate: +startDate,
				endDate: +endDate
			})
			.then(function(response){
				var performances;
				if(response){
					performances = Ember.A(response[appId]);
					ctrl.set("model.threshold", response.threshold);
				}else{
					performances = Ember.A();
				}
				performances = ctrl.get("controllers.businessCenter")
					.performancesCompletion(performances, startDate, endDate);
				// ctrl.set('axisLength',performances.length);
				ctrl.set("model.performances", performances);
				ctrl._setAppXAxisTime();
				return performances;
			});
		},

		/*
			向服务端请求某个月的概览模式的性能数据
		*/
		requirePerformancesByMonth: function(){
			var ctrl = this;
			var appId = this.get("model.id");
			var dateValue = this.get("historyDate.value");
			if(!appId){
				return;
			}

			var now = new Date(new Date() - timeD_value);
			if(dateValue){
				now = new Date(dateValue);
			}
			if( isLocalDebugModel ){
				now = new Date(2014, 9, 1, 12, 0, 0);
			}
			var startDate = new Date(now.getFullYear(), now.getMonth(), 1);
			var endDate = new Date(now.getFullYear(), now.getMonth()+1, 1);

			return this.store.ajax("GET", "performances", {
				appIds: appId,
				startDate: +startDate,
				endDate: +endDate,
				size: "hour"
			})
			.then(function(response){
				var arr = Ember.A(response[appId]);
				arr = ctrl.performancesCompletionByMonth(arr, startDate, endDate);
				ctrl.set("sequenceDataOneMonth", Ember.A(arr));
				return arr;
			});
		},

		/*
			自动补全月份性能数据
			@param {array} performances 性能数组
			@param {date} startDate 月初开始时间
		*/
		performancesCompletionByMonth: function(performances, startDate, endDate){
			startDate = new Date(+startDate),
			endDate = new Date(+endDate);

			if(!startDate && !endDate){
				Ember.assert("startDate, 或者endDate参数不是时间");
				return;
			}

			performances = performances||[];

			startDate.setMinutes(0);
			startDate.setSeconds(0);
			startDate.setMilliseconds(0);
			endDate.setMinutes(0);
			endDate.setSeconds(0);
			endDate.setMilliseconds(0);

			var performancesMap = {};
			for(var i = performances.length-1 ; i >= 0 ; i--){
				performancesMap[performances[i].timestamp] = performances[i];
			}

			var timestamp = +startDate,
				newPerformances = [];
			for(; timestamp < +endDate ; timestamp += 3600000){
				if(!performancesMap[timestamp]){
					newPerformances.push({"timestamp": timestamp});
				}else{
					newPerformances.push(performancesMap[timestamp]);
				}
			}

			return Ember.A(newPerformances);
		},

		reset: function(){
			this.set("model", null);
			this.set("sequenceData", null);
			this.set("pinTimePoint", null);
		},

		isTradingModeChange: Ember.observer("businessSwitch",function(key,value){
			if(this.get("businessSwitch") == "business"){
				this.set("isTradingMode",true);
			}else{
				this.set("isTradingMode",false);
			}
		}),
		
		// isTradingModeChange: Ember.observer("isOverviewTradingMode",function(){
		// 	alert(1);
		// 	this.set("isOverviewTradingMode",false);
		// 	this.set("isTradingMode",true);
		// 	// if(this.get("isOverviewTradingMode")){
		// 	// 	this.set("isTradingMode",true);
		// 	// 	this.set("isOverviewTradingMode",false);
		// 	// }
		// 	// if(this.get("isCenterTradingMode")){
		// 	// 	this.set("isTradingMode",false);
		// 	// 	this.set("isCenterTradingMode",false);
		// 	// }
		// }),
		// isCenterTradingModeChange: Ember.observer("isCenterTradingMode",function(){
		// 	alert(2);
		// 	this.set("isTradingMode",false);
		// 	// this.set("isOverviewTradingMode",false);
		// 	// this.set("isTradingMode",true);
		// 	// if(this.get("isOverviewTradingMode")){
		// 	// 	this.set("isTradingMode",true);
		// 	// 	this.set("isOverviewTradingMode",false);
		// 	// }
		// 	// if(this.get("isCenterTradingMode")){
		// 	// 	this.set("isTradingMode",false);
		// 	// 	this.set("isCenterTradingMode",false);
		// 	// }
		// }),
		actions: {
			dropdown:function(){
				var ctrl = this;
				if(!ctrl.get("dropdown")){
					ctrl.set("dropdown",true);
					$(".dropdown-select").addClass("open");
				}else{
					ctrl.set("dropdown",false);
					$(".dropdown-select").removeClass("open");
				}
				$(document).on("click",function(){
					$(".dropdown-select").removeClass("open");
					ctrl.set("dropdown",false);
				});
			},
			dropdown2:function(){
				var ctrl = this;
				if(!ctrl.get("dropdown2")){
					ctrl.set("dropdown2",true);
					$(".dropdown2-select").addClass("open");
				}else{
					ctrl.set("dropdown2",false);
					$(".dropdown2-select").removeClass("open");
				}
				$(document).on("click",function(){
					$(".dropdown2-select").removeClass("open");
					ctrl.set("dropdown2",false);
				});
			},
			dropdown3:function(){
				var ctrl = this;
				if(!ctrl.get("dropdown3")){
					ctrl.set("dropdown3",true);
					$(".dropdown3-select").addClass("open");
				}else{
					ctrl.set("dropdown3",false);
					$(".dropdown3-select").removeClass("open");
				}
				$(document).on("click",function(){
					$(".dropdown3-select").removeClass("open");
					ctrl.set("dropdown3",false);
				});
			},
			gotoOtherApp: function(app){
				if(app.id){
					this.transitionToRoute("business.detail", app.id);
				}
			},
			thresholdOrTrading: function(num){
				if(((overviewOrCenterSwitch === "business")&&num)||((overviewOrCenterSwitch !== "business")&&!num)){
					return;
				}
				var appData = this.get("model.id");
				if(overviewOrCenterSwitch == "system"){
					$.cookie("isThreshold", "business", '/');
					
				}else{
					$.cookie("isThreshold", "system", '/');
				}

				if($.cookie("isThreshold") == "business"){
					this.set("isTradingMode",true);
				}else{
					this.set("isTradingMode",false);
				}
				window.location.reload();

				var currentURL = window.location.href.substring(0,window.location.href.lastIndexOf("/"));
				var scrrenString = window.location.href.indexOf;

				if(window.location.href.indexOf("gauge") === -1 &&window.location.href.indexOf("config") === -1 && window.location.href.indexOf("default") === -1 && window.location.href.indexOf("browser") === -1 && window.location.href.indexOf("page") === -1 && window.location.href.indexOf("area") === -1){
					if(num == 1){
						window.location.href = currentURL+"/overview";
					}
				}
				
	
				
				//嵌入COSS里刷新页面改变地址的处理
				if($.cookie("cossembed")){
					if(window.location.href.indexOf("hidden") == -1){
						window.location.href = window.location.href+"?hidden";
					}
					
				}	

			},
			sequenceItemClick: function(args, view){
				switch(view.displayMode){
					case "overview":
						this.send("showDetail", args, view);
						this.set("selectedFormatedDate", args.timestamp);
						this.set("clickFormatedDate", args.timestamp);
						break;
					case "detail":
						if(this.get("pinTimePoint") == args.timestamp){
							this.set("pinTimePoint", null);
						}else{
							this.set("pinTimePoint", args.timestamp);
						}
						this.set("timePoint", args.timestamp);
						this.set("clickTimePoint", args.timestamp);
						this.set("isSelectedTime",true);
						break;
				}
			},

			sequencehoverItemChanged: function(args, view){
				if(view.displayMode == "detail"){
					this.set("timePoint", args.timestamp);
				}
			},

			mouseoutSequenceChart: function(view){
				if(view.displayMode == "overview"){
					return;
				}
				if( this.get("pinTimePoint") ){
					this.set("timePoint", this.get("pinTimePoint"));
				}else{
					var performances = this.get("model.performances");
					if(performances && performances.length>0){
						var timePoint = performances[performances.length-1].timestamp;
						this.set("timePoint", timePoint);
					}
				}
			},

			showDetail: function(data, view){
				var ctrl = this;
				var time = data.timestamp;

				ctrl.set("sequenceChartDisplayMode", "detail");
				this.requirePerformances(time);
			},

			backToOverview: function(){
				this.set("selectedFormatedDate", null);
				this.set("clickFormatedDate", null);
				this.set("sequenceChartDisplayMode", "overview");
			},

			toggleRealtimeMode: function(num){
				var ctrl = this;
				var isRealtimeMode = this.get("isRealtimeMode");
				if(num == isRealtimeMode){
					return;
				}
				if(this.get("isRealtimeMode")){
					this.stopRealTimeMode();
					this.requirePerformancesByMonth();

					this.set("selectedFormatedDate", null);
					this.set("clickFormatedDate", null);
					this.set("sequenceChartDisplayMode", "overview")
				}else{
					ctrl.startRealTimeMode();
					this.requirePerformances();

					ctrl.set("sequenceChartDisplayMode", "detail");
				}
			},

			queryByMonth: function(){
				var date = this.get("selctedDate");

				this.set("historyDate", new Date(date.getFullYear(), date.getMonth(), 1));
				this.set("sequenceChartDisplayMode", "overview");
				this.set("isMonthSelectorShow", false);

				this.requirePerformancesByMonth();

				this.set("selectedFormatedDate", null);
				this.set("clickFormatedDate", null);
			},

			toggleMonthSelector: function(){
				this.set("isMonthSelectorShow", !this.get("isMonthSelectorShow"));
			}
		}
	});

	APM.BusinessDetailController = Controller;
		return Controller;
	}
);